// pages/login/login.js
import { Login } from '../../models/login'

const loginModel = new Login()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    sessionKeyVal: '123',
    phoneNumber: '',
    selectNumber: 0,
    sms: '',
    sendCode: '',
    password: '',
    sendStatus: true,
    time: 60,
    showAll: false,
    canIUseGetUserProfile: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
    let vm = this
    wx.login({
      success(res) {
        loginModel.code2Session(
          {
            code: res.code
          },
          (res) => {
            vm.data.sessionKeyVal = res.session_key
          }
        )
      }
    })
  },

  /*
   * 登录
   * */
  login() {
    this.data.selectNumber === 0 ? this.fastLogin() : this.normalLogin()
  },

  fastLogin() {
    console.log('快捷登录')
    let params = {
      tel: this.data.phoneNumber,
      code: this.data.sms,
      RegistrationID: 0,
      SendCode: this.data.sendCode
    }
    loginModel.GetUserQuickLogin(params, (resB) => {
      loginModel.getUserToken(
        {
          type: 2,
          userId: resB.user_id,
          userName: resB.mobile
        },
        (resC) => {
          wx.setStorageSync('userToken', resC)
        }
      )
      wx.setStorageSync('userInfo', resB)
      this._getGetMyDistributionYard()
      wx.navigateBack({
        delta: 1
      })
    })
  },

  normalLogin() {
    let params = {
      username: this.data.phoneNumber,
      password: this.data.password,
      RegistrationID: 0
    }
    loginModel.GetUserLogin(params, (resB) => {
      loginModel.getUserToken(
        {
          type: 2,
          userId: resB.user_id,
          userName: resB.mobile
        },
        (resC) => {
          wx.setStorageSync('userToken', resC)
        }
      )
      wx.setStorageSync('userInfo', resB)
      this._getGetMyDistributionYard()
      wx.navigateBack({
        delta: 1
      })
    })
  },

  dontLogin() {
    // 不登录 跳转到首页
    wx.switchTab({
      url: '/pages/main/main'
    })
  },

  /*
   * 获取分销码
   * */
  _getGetMyDistributionYard() {
    loginModel.GetMyDistributionYard((res) => {
      console.log(res)
      wx.setStorageSync('shareCode', res.distribution_yard)
    })
  },

  /*
   *  获取微信用户信息
   * */

  onGotUserInfo: function (e) {
    console.log(e)
    let params = {
      encryptedData: e.detail.encryptedData,
      sessionKey: this.data.sessionKeyVal,
      iv: e.detail.iv
    }
    loginModel.getAESDecrypt(params, (res) => {
      console.log(res)
      this._getAddWXUser(res)
    })
  },

  phoneLogin() {
    this.setData({
      showAll: true
    })
  },

  goreg() {
    wx.navigateTo({
      url: '/pages/register/register'
    })
  },

  /*
   *  用户微信登录
   * */

  _getAddWXUser: function (resA) {
    let params = {
      open_id: resA.openId,
      zlrOpenid: resA.openId,
      platform: 2,
      unionid: resA.unionId,
      nickname: resA.nickName,
      avatar: resA.avatarUrl,
      distribution_yard: wx.getStorageSync('otherCode')
        ? wx.getStorageSync('otherCode')
        : ''
    }
    loginModel.getAddWXUser(params, (resB) => {
      console.log(resB)
      // res.user_id ='136120'
      loginModel.getUserToken(
        {
          openCode: resA.unionId,
          type: 1,
          userId: resB.user_id,
          userName: ''
        },
        (resC) => {
          wx.setStorageSync('userToken', resC)
          // 判断是否为初次进入小程序 送上级红包
          const isFirstJoin = wx.getStorageSync('isFirstJoin') || false
          const otherId = wx.getStorageSync('otherId') || ''
          console.error(typeof isFirstJoin, isFirstJoin)
          if (!isFirstJoin) {
            // 初次进入，未登录
            console.error('进入判断', otherId)
            wx.setStorageSync('isFirstJoin', true)
            loginModel.giveShareLoginAward({
              shareUserId: otherId
            })
          }
        }
      )
      wx.setStorageSync('userInfo', resB)
      this._getGetMyDistributionYard()
      wx.navigateBack({
        delta: 1
      })
    })
  },
  /*
   * 选择哪一种登录方式
   * */
  selectIndex(e) {
    console.log(e.detail.index)
    this.setData({
      selectNumber: e.detail.index
    })
  },

  setPhoneNumber(event) {
    console.log(event.detail)
    this.setData({
      phoneNumber: event.detail
    })
  },

  setSms(event) {
    this.setData({
      sms: event.detail
    })
  },

  setPassword(event) {
    console.log(event.detail)
    this.setData({
      password: event.detail
    })
  },
  /*
   * 获取验证码
   * */
  sendSms(e) {
    console.log(e)
    if (!this.data.sendStatus) {
      return
    }
    let params = {
      mobile: this.data.phoneNumber,
      sendType: '2'
    }
    loginModel.GetSMSCode(
      params,
      (res) => {
        console.log(res)
        this.switchComputed()
        this.setData({
          sendCode: res.SMSCode,
          time: 60
        })
      },
      (err) => {
        let vm = this
        wx.showModal({
          title: '温馨提示',
          content: '您还没有注册，先去完成注册哦！',
          success(res) {
            if (res.confirm) {
              wx.navigateTo({
                url: `/pages/register/register`
              })
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
    )
  },

  switchComputed() {
    this.setData({
      sendStatus: false
    })
    let allTime = 60
    let computedTime = setInterval(() => {
      this.setData({
        time: allTime--
      })
      if (this.data.time === 0) {
        clearInterval(computedTime)
        this.setData({
          sendStatus: true
        })
      }
    }, 1000)
  },

  register() {
    wx.navigateTo({
      url: `/pages/register/register`
    })
  },

  forgetPass() {
    wx.navigateTo({
      url: `/pages/forget/forget`
    })
  },

  dontLogin() {
    // 不登录 跳转到首页
    wx.switchTab({
      url: '/pages/main/main'
    })
  },

  getUserProfile() {
    // console.log(1111);
    let userInfo = {}
    wx.getUserInfo({
      success: function (res) {
        userInfo = res
      }
    })
    wx.getUserProfile({
      desc: '用于完善会员资料',
      success: (resA) => {
        let params = {
          encryptedData: userInfo.encryptedData,
          sessionKey: this.data.sessionKeyVal,
          iv: userInfo.iv
        }
        loginModel.getAESDecrypt(params, (resB) => {
          resB.nickName = resA.userInfo.nickName
          resB.avatarUrl = resA.userInfo.avatarUrl
          this._getAddWXUser(resB)
        })
      }
    })
  }
})
